<template>
	<view class="container">
		<view class="navbar">
			<button type="default" plain class="talk-btn" @click="toDescription()">
				<image src="/static/images/order/order_icon_talk2.0.png"></image>
				<view>订单说明</view>
			</button>
		</view>
		<view class="tabbar">
			<view class="item" :class="{active: !tabIndex}" @tap="switchTab(0)">当前订单</view>
			<view class="item" :class="{active: tabIndex}" @tap="switchTab(1)">历史订单</view>
		</view>
		<swiper :current="tabIndex" :duration="300" class="swiper" :show-scrollbar="false">
			<!-- 当前订单 begin -->
			<swiper-item v-if="orders.length<1" @touchmove.stop="handleSwiperItemChange">
				<view class="no-order-content">
					<image src="../../static/images/order/default_img_order.png"></image>
					<view class="tips">
						<view>您今天还没有下单</view>
						<view>快去选择一款喜欢的镜片吧</view>
					</view>
					<button type="primary" class="font-size-lg" hover-class="none" @click="toProdutList()">去下单</button>
				</view>
			</swiper-item>
			<!-- 当前订单 begin -->
			<swiper-item v-else @touchmove.stop="handleSwiperItemChange">
				<scroll-view scroll-y="true" class="orders-scroll" style="padding-top:0px;">
					<view class="wrapper">
						<view class="order-list">
							<navigator class="order" v-for="(order, index) in orders" :key="index" open-type="navigate">
								<view class="header">
									<view class="flex-fill font-size-medium">{{order.ooutTradeNo[0].CoName}}</view>
									<view class="status">
										<view>{{order.oStatus==0?"未支付":"已完成"}}</view>
										<image src="/static/images/common/black_arrow_right.png"></image>
									</view>
								</view>
								<scroll-view scroll-x>
									<view class="images">
										<image :src="item.osProImg" v-for="(item, index) in order.lx_Self_OrdersSub" :key="index"></image>
									</view>
								</scroll-view>
								<view class="info">
									<view class="left">
										<view>订单编号：{{ order.oCode }}</view>
										<view>下单时间：{{ order.createDate }}</view>
									</view>
									<view class="right">
										￥{{ (parseFloat(order.oAllPrice)+parseFloat(order.ojgPrice)) }}
									</view>
								</view>
								<view class="action">
									<button type="default" v-if="order.oStatus==1" hover-class="none" @click="toPublishPage(order)">评价</button>
									<button type="default" hover-class="none" @click="toDetail(order)">查看评论</button>
									<button v-if="order.oStatus==0" type="primary" plain hover-class="none" @click="weixinPay(order.id)">去支付</button>
								</view>
							</navigator>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
			<!-- 当前订单 end -->

			<!-- 当前订单 end -->
			<!-- 历史订单 begin -->
			<swiper-item @touchmove.stop="handleSwiperItemChange">
				<view class="history-order">
					<view class="menu">
						<view class="flex-fill d-flex justify-content-start">
							<view class="item" :class="{active: !orderMenuIndex}" @tap="switchMenuTab(0)">门店订单</view>
							<view class="item" :class="{active: orderMenuIndex}" @tap="switchMenuTab(1)">百货订单</view>
						</view>
						<view class="item" v-show="batchInvoiceVisible">
							<image src="/static/images/order/batch_invoice_icon.png"></image>
							<view>批量开票</view>
						</view>
					</view>
					<swiper :current="orderMenuIndex" :duration="300" :show-scrollbar="false" class="history-order-swiper">
						<!-- 门店订单 begin -->
						<swiper-item @touchmove.stop="handleSwiperItemChange">
							<swiper-item v-if="orders.length<1" @touchmove.stop="handleSwiperItemChange">
								<view class="no-order-content">
									<image src="../../static/images/order/default_img_order.png"></image>
									<view class="tips">
										<view>您今天还没有下单</view>
										<view>快去选择一款喜欢的镜片吧</view>
									</view>
									<button type="primary" class="font-size-lg" hover-class="none" @click="toProdutList()">去下单</button>
								</view>
							</swiper-item>
							
							<scroll-view v-else scroll-y="true" class="orders-scroll">
								<view class="wrapper">
									<view class="order-list">
										<navigator class="order" v-for="(order, index) in orders" :key="index" open-type="navigate">
											<view class="header">
												<view class="flex-fill font-size-medium">{{order.ooutTradeNo[0].CoName}}</view>
												<view class="status">
													<view>已完成</view>
													<image src="/static/images/common/black_arrow_right.png"></image>
												</view>
											</view>
											<scroll-view scroll-x>
												<view class="images">
													<image :src="item.osProImg" v-for="(item, index) in order.lx_Self_OrdersSub" :key="index"></image>
												</view>
											</scroll-view>
											<view class="info">
												<view class="left">
													<view>订单编号：{{ order.oCode }}</view>
													<view>下单时间：{{ order.createDate }}</view>
												</view>
												<view class="right">
													￥{{ (parseFloat(order.oAllPrice)+parseFloat(order.ojgPrice)) }}
												</view>
											</view>
											<view class="action">
												<button type="default" hover-class="none" @click="toPublishPage(order)">p</button>
												<button type="default" hover-class="none" @click="toDetail(order)">评价</button>
												<button v-if="order.oStatus==0" type="primary" plain hover-class="none" @click="weixinPay(order.id)">去支付</button>
											<!-- 	<button type="primary" plain hover-class="none">再来一单</button> -->
											</view>
										</navigator>
									</view>
								</view>
							</scroll-view>
						</swiper-item>
						<!-- 门店订单 end -->
						<!-- 百货订单 begin -->
						<swiper-item @touchmove.stop="handleSwiperItemChange">
							<view class="store-order-wrapper">
								<image src="/static/images/order/default_img_order.png"></image>
								<view>您还没有下单</view>
								<view>快去百货商城逛逛吧</view>
							</view>
						</swiper-item>
						<!-- 百货订单 end -->
					</swiper>
				</view>
			</swiper-item>
			<!-- 历史订单 end -->
		</swiper>
		<!-- <image src="https://go.cdn.heytea.com/storage/ad/2020/05/20/1a389117c2fb44d5bcad4a910a68246c.jpg"></image> -->
	</view>
</template>


<script>
	import {
		mapState
	} from 'vuex'

	export default {
		data() {
			return {
				payOptions:{},
				tabIndex: 0,
				orderMenuIndex: 0,
				orders: [],
				storeOrders: []
			}
		},
		async onLoad() {
			await this.getOrders();
		},
		computed: {
			batchInvoiceVisible() {
				return (!this.orderMenuIndex && this.orders.length) || (this.orderMenuIndex && this.storeOrders.length)
			},
			...mapState(['isLogin', 'userInfo'])
		},
		methods: {
			async switchTab(index) {
				if (this.tabIndex === index) return
				this.tabIndex = index
				await this.getOrders()
				// if (this.tabIndex) {

				// }
			},
			handleSwiperItemChange() { //禁止手动滑动
				return true
			},
			async switchMenuTab(index) {
				if (this.orderMenuIndex === index) return
				this.orderMenuIndex = index
				await this.getOrders()
			},
			//   async getOrders() {
			// 	if(!this.orderMenuIndex) {
			// 		this.orders = await this.$api('orders')
			// 	} else {
			// 		this.storeOrders = await this.$api('storeOrders')
			// 	}
			// },
			//获取服务器订单数据
			getOrders() {
				if (!this.isLogin) {
					return;
				}
				let that = this;
				let whe = [];
				whe.push({
					"name": "OStatus",
					"value": that.tabIndex == 0 ? 4 : 3,
					"displayType": that.tabIndex == 0 ? "LT" : "GT" //<>
				});
				let coid = uni.getStorageSync('coid');
				whe.push({
					"name": "OCusId",
					"value": uni.getStorageSync('WxId'),
					"displayType": "text" 
				});

				let cateOp = {
					url: "api/Lx_Self_Orders/UI_GetPageData",
					data: {
						"page": 1,
						"rows": 10,
						"sort": 'Id',
						wheres: JSON.stringify(whe)
					}
				}

				this.$request.Post(cateOp, (ret) => {
					if (ret.rows.length > 0) {
						that.orders = [];
						that.orders = ret.rows;
						that.orders.map(e => {
							//将店铺数据 转成json格式
							e.ooutTradeNo = JSON.parse(e.ooutTradeNo);
							return e;
						});

					}
				});
			},
			toDetail(order) {
				let orderStr = JSON.stringify(order);
				let url = `/pages/order/detail?order=${orderStr}`;
				uni.navigateTo({
					url: url
				});
			},
			//去下单
			toProdutList(){
				uni.switchTab({
					url: `/pages/index/index`
				});
			},
			//订单说明
			toDescription(order) {
				uni.navigateTo({
					url: `/pages/order/components/description/description`
				});
			},
			//评论
			toPublishPage(order) {
				let orderStr = JSON.stringify(order);
				uni.navigateTo({
					url: `/pages/order/components/publish/publish?order=${orderStr}`
				});
			},
			
			
			//微信小程序内支付
			weixinPay(orderId) {
				console.log("发起支付");
				let that = this;
				this.loading = true;
				
				uni.login({
					success: (e) => {
						console.log("login success", e);//wxOpenId
						var userOpenid = wx.getStorageSync("wxOpenId");
						console.log(userOpenid);
						//获取支付参数
						let cateOp = {
							url: `api/Sys_User/WxPayH5?orderId=${orderId}&feed=&userId=${wx.getStorageSync("WxId")}&apiType=${userOpenid}`,
							data: ""
						}
						this.$request.Post(cateOp, (res) => {
							that.payOptions = JSON.parse(res.data);
							console.log("pay request success", res);
							console.log("得到接口prepay_id", res.data);
							let paymentData = JSON.parse(res.data);
							uni.requestPayment({
								timeStamp: paymentData.timestamp,
								nonceStr: paymentData.noncestr,
								package: paymentData.package,
								signType: 'MD5',
								paySign: paymentData.sign,
								success: (res) => {
									uni.showToast({
										title: "支付成功!"
									});
									//that.payResultHandler(orderId);
									uni.navigateTo({
										url: `/pages/order/order`
									});
								},
								fail: (res) => {
									uni.showModal({
										content: "支付失败!",
										showCancel: false
									});
									uni.navigateTo({
										url: `/pages/order/order`
									});
								},
								complete: () => {
									this.loading = false;
								}
							})
						});
			
					},
					fail: (e) => {
						console.log("fail", e);
						this.loading = false;
						uni.showModal({
							content: "支付失败!",
							showCancel: false
						})
					}
				})
			},
			
			//查询订单是否支付成功 并且完成后续任务。
			payResultHandler(orderId) {
				let feed=this.cartAmount();
				let Op = {
					url: "api/Sys_User/QueryOrderPayResult?outTradeNo=" + this.payOptions.tradeno + "&payType=3&feed=" +feed +
						"&userId=" + wx.getStorageSync("WxId") + "&orderId=" + orderId,
					data: ""
				}
				this.$request.Post(Op, (ret) => {
					uni.navigateTo({
						url: `/pages/order/order`
					});
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #f6f6f6;
	}

	.navbar {
		height: calc(44px + var(--status-bar-height));
		/* #ifdef H5 */
		height: 44px;
		/* #endif */
		display: flex;
		background-color: #FFFFFF;
	}

	.talk-btn {
		height: 32px;
		margin-left: 10px;
		margin-top: 26px;
		/* #ifdef H5 */
		margin-top: 6px;
		/* #endif */
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: $font-size-sm !important;
		padding: 0 20rpx;
		border-radius: 50rem !important;

		image {
			width: 40rpx;
			height: 40rpx;
			margin-right: $spacing-row-sm;
		}
	}

	.tabbar {
		height: 100rpx;
		background-color: $bg-color-white;
		display: flex;
		align-items: center;
		justify-content: space-around;

		.item {
			height: 100%;
			font-size: $font-size-lg;
			color: $text-color-assist;
			font-weight: 400 !important;
			display: flex;
			align-items: center;

			&.active {
				color: $text-color-base;
				border-bottom: 4rpx solid $text-color-base;
			}
		}
	}

	.swiper {
		width: 100%;
		height: calc(100vh - 44px - var(--status-bar-height) - 110rpx);
		/* #ifdef H5 */
		height: calc(100vh - 44px - var(--status-bar-height) - 110rpx - 100rpx);
		/* #endif */
	}

	.no-order-content {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		image {
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 50rpx;
		}

		.tips {
			color: $text-color-assist;
			display: flex;
			flex-direction: column;
			align-items: center;
			line-height: 1.2rem !important;
			margin-bottom: 70rpx;
		}

		button {
			width: 50%;
		}
	}

	.history-order {
		width: 100%;
		height: 100%;
		position: relative;

		.menu {
			padding: 18rpx 30rpx;
			display: flex;
			align-items: center;
			font-size: $font-size-base;
			color: $text-color-grey;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 10;

			.item {
				padding: 14rpx 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}

				&.active {
					color: $color-primary;
					background-color: $bg-color-white;
				}
			}
		}

		.history-order-swiper {
			width: 100%;
			height: 100%;
		}
	}

	.store-order-wrapper {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: $font-size-base;
		color: $text-color-assist;
		line-height: 1.3rem !important;

		image {
			width: 400rpx;
			height: 333rpx;
			margin-bottom: 40rpx;
		}
	}

	.orders-scroll {
		width: 100%;
		height: 100%;
		padding-top: 104rpx;
	}

	.order-list {
		display: flex;
		width: 100%;
		flex-direction: column;

		.order {
			background-color: $bg-color-white;
			padding: 30rpx 40rpx;
			margin-bottom: 18rpx;

			.header {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.status {
					font-size: $font-size-base;
					color: $text-color-grey;
					display: flex;
					align-items: center;

					image {
						width: 30rpx;
						height: 30rpx;
						margin-left: $spacing-row-sm;
					}
				}
			}

			.images {
				display: flex;
				padding: 30rpx 0;

				image {
					flex-shrink: 0;
					width: 150rpx;
					height: 112.5rpx;
				}
			}

			.info {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				.left {
					flex: 1;
					display: flex;
					flex-direction: column;
					font-size: $font-size-base;
					color: $text-color-grey;
				}

				.right {
					font-size: $font-size-lg;
					color: $text-color-base;
				}
			}

			.action {
				display: flex;
				justify-content: flex-end;
				align-items: center;

				button {
					margin-left: 30rpx;
					font-size: $font-size-sm;
				}
			}
		}
	}
</style>
